package com.lanou.moving.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.lanou.moving.R;
import com.lanou.moving.activity.MainActivity;
import com.lanou.moving.activity.PlayMusicActivity;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.receiver.ServiceReceiver;
import com.lanou.moving.shake.ShakeDetector;
import com.lanou.moving.utils.MyConfig;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import de.greenrobot.event.EventBus;

/**
 * Created by 刘琪 on 15/10/30.
 */
public class MyService extends Service implements ShakeDetector.OnShakeListener {
    public static final String BROADCAST_NAME = "com.lanou.moving.broadcast";
    public static final String BROADCAST_SHAKE = "com.lanou.moving.shake";
    public static final String SHAKE_ON_OFF = "SHAKE_ON_OFF";

    private static MediaPlayer mediaPlayer;
    private static String path;
    private List<MusicInfo> musicInfoList;
    private MusicInfo musicInfo;
    private int position;
    private String url;
    private int playState;//播放状态
    private RemoteViews remoteViews;
    private NotificationCompat.Builder builder;
    private NotificationManager                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      manager;

    private ShakeDetector shakeDetector;
    private MusicPlayBroadcast mPlayBroadcast;
    /**
     * 在设置界面是否开启了摇一摇的监听
     */
    public boolean mShake;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MediaBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        init();
        shakeDetector = new ShakeDetector(this);
        shakeDetector.setOnShakeListener(this);
        mPlayBroadcast = new MusicPlayBroadcast();
        IntentFilter filter = new IntentFilter(BROADCAST_NAME);
        filter.addAction(BROADCAST_SHAKE);
        registerReceiver(mPlayBroadcast, filter);
    }

    private void init() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaPlayer.reset();
                EventBus.getDefault().post(new MyEventBus.PlayControl(4));
            }
        });
    }

    private class MusicPlayBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(BROADCAST_NAME)) {
                if (mediaPlayer.isPlaying()) {
                        shakeDetector.start();
                }else {
                    shakeDetector.stop();
                }
            } else if (intent.getAction().equals(BROADCAST_SHAKE)) {
                mShake = intent.getBooleanExtra(SHAKE_ON_OFF, false);
                if (mShake && mediaPlayer.isPlaying()) {//如果开启了监听并且歌曲正在播放
                    shakeDetector.start();
                } else if (!mShake) {
                    shakeDetector.stop();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static void setUrl(final String url) {
        path = url;
    }

    public void play() {
        musicInfo = musicInfoList.get(position);
        url = musicInfo.getUrl();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void onEvent(MyEventBus.PlayMusic playMusic) {
        switch (playMusic.getWhat()) {
            case 1:
                play();
                break;
            case 2:
                remoteViews.setImageViewResource(R.id.play_pause_music, R.mipmap.music_play);
                manager.notify(1, builder.build());
                mediaPlayer.pause();
                break;
            case 3:
                remoteViews.setImageViewResource(R.id.play_pause_music, R.mipmap.music_pause);
                manager.notify(1, builder.build());
                mediaPlayer.start();
                break;
        }
    }

    @Override
    public void onShake() {
        EventBus.getDefault().post(new MyEventBus.PlayControl(3));
    }


    public class MediaBinder extends Binder {

        public int getCurrentPosition() {
            return mediaPlayer.getCurrentPosition();
        }

        // 拖动seekBar调用的方法
        public void seekTo(int index) {
            mediaPlayer.seekTo(index);
        }

        // 获取音乐时长
        public int getMax() {
            return mediaPlayer.getDuration();
        }

        // 获取歌曲名
        public String getSongName() {
            return musicInfo.getSongName();
        }

        // 获取歌手名
        public String getSingerName() {
            return musicInfo.getSingerName();
        }

        // 获取专辑id
        public int getAlbumId() {
            return musicInfo.getAlbumId();
        }

        // 获取当前播放列表
        public List<MusicInfo> getMusicInfoList() {
            return musicInfoList;
        }

        // 获取当前播放音乐的位置
        public int getPosition() {
            return position;
        }

        // 判断歌曲来源
        public String getResouce() {
            return musicInfoList.get(position).getResouce();
        }

        // 获取歌曲的url
        public String getUrl() {
            return musicInfoList.get(position).getUrl();
        }

        // 获取歌曲id
        public long getSongId() {
            return musicInfoList.get(position).getSongId();
        }

    }

    private void showCustomView(String songName, String singerName) {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        remoteViews = new RemoteViews(getPackageName(),
                R.layout.music_notification);
        // 设置textview
        remoteViews.setTextViewText(R.id.songName, songName);
        remoteViews.setTextViewText(R.id.singerName, singerName);

        // 设置按钮事件 -- 发送广播 --广播接收后进行对应的处理

        Intent buttonPlayIntent = new Intent(
                ServiceReceiver.NOTIFICATION_ITEM_BUTTON_LAST); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent = PendingIntent.getBroadcast(this,
                0, buttonPlayIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.last_music,
                pendButtonPlayIntent);// ----设置对应的按钮ID监控

        Intent buttonPlayIntent1 = new Intent(
                ServiceReceiver.NOTIFICATION_ITEM_BUTTON_PLAY); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent1 = PendingIntent.getBroadcast(this,
                0, buttonPlayIntent1, 0);
        remoteViews.setOnClickPendingIntent(R.id.play_pause_music,
                pendButtonPlayIntent1);// ----设置对应的按钮ID监控

        Intent buttonPlayIntent2 = new Intent(
                ServiceReceiver.NOTIFICATION_ITEM_BUTTON_NEXT); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent2 = PendingIntent.getBroadcast(this,
                0, buttonPlayIntent2, 0);
        remoteViews.setOnClickPendingIntent(R.id.next_music,
                pendButtonPlayIntent2);// ----设置对应的按钮ID监控

        builder = new NotificationCompat.Builder(this);
        Intent intent = new Intent(this, PlayMusicActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 67, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);
        builder.setContent(remoteViews).setSmallIcon(R.mipmap.moving)
                .setOngoing(true).setTicker("music is playing");

        manager.notify(1, builder.build());

    }

    // 接收数据
    public void onEvent(MyEventBus.Deliver deliver) {
        musicInfoList = deliver.getMusicInfos();
        String songName = deliver.getSongName();
        for (int i = 0; i < musicInfoList.size(); i++) {
            if (musicInfoList.get(i).getSongName().equals(songName)) {
                position = i;
                break;
            }
        }
        play();
        showCustomView(musicInfoList.get(position).getSongName(), musicInfoList.get(position).getSingerName());
    }

    public void onEvent(MyEventBus.OpenMusic openMusic) {
        if (openMusic.isOpen() == true) {
            showCustomView(musicInfoList.get(position).getSongName(), musicInfoList.get(position).getSingerName());
            EventBus.getDefault().post(new MyEventBus.RefreshUI(mediaPlayer != null));
        }
    }

    public void onEvent(MyEventBus.PlayControl playControl) {
        switch (playControl.getWhat()) {
            case 2://上一首
                if (playState == 0) {//列表循环
                    if (position == 0) {
                        position = musicInfoList.size() - 1;
                    } else {
                        position--;
                    }
                }
                if (playState == 1) {//单曲循环
                    if (position == 0) {
                        position = musicInfoList.size() - 1;
                    } else {
                        position--;
                    }
                }
                if (playState == 2) {//随机播放
                    // 产生随机数
                    position = new Random().nextInt(musicInfoList.size() - 1);
                }
                play();
                break;
            case 3://下一首
                if (playState == 0) {//列表循环
                    if (position == musicInfoList.size() - 1) {
                        position = 0;
                    } else {
                        position++;
                    }
                }
                if (playState == 1) {//单曲循环
                    if (position == musicInfoList.size() - 1) {
                        position = 0;
                    } else {
                        position++;
                    }
                }
                if (playState == 2) {//随机播放
                    // 产生随机数
                    position = new Random().nextInt(musicInfoList.size() - 1);
                }
                play();
                break;
            case 4:
                if (playState == 0) {//列表循环
                    if (position == musicInfoList.size() - 1) {
                        position = 0;
                    } else {
                        position++;
                    }
                }
                if (playState == 1) {//单曲循环

                }
                if (playState == 2) {//随机播放
                    // 产生随机数
                    position = new Random().nextInt(musicInfoList.size() - 1);
                }
                play();
                break;
        }
        showCustomView(musicInfoList.get(position).getSongName(), musicInfoList.get(position).getSingerName());
    }

    public void onEvent(MyEventBus.PlayMode playMode) {
        playState = playMode.getPlayMode();
    }

    // 点击播放列表,改变当前播放音乐
    public void onEvent(MyEventBus.ChangeMusic changeMusic) {
        position = changeMusic.getPosition();
        play();
    }
}
